package com.home.zqt.platform.configure;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.beetl.sql.core.DSTransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @author soon
 * @description: TODO
 * @date 2019-06-03 20:27
 **/
@Aspect
@Component
public class TransactionAdvice {

    private static final Logger LOG = LoggerFactory.getLogger(TransactionAdvice.class);

    @Pointcut("execution(* com.home.zqt.platform.service..*.*(..))")
    public void doTransaction() {}

    @Around("doTransaction()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        try {
            LOG.info("start transaction......");
            DSTransactionManager.start();
            Object result = pjp.proceed();
            DSTransactionManager.commit();
            LOG.info("end transaction......");
            return result;
        } catch (Throwable t) {
            LOG.error(t.getMessage(), t);
            try {
                DSTransactionManager.rollback();
            } catch (SQLException sqlE) {
                throw sqlE;
            }
            throw t;
        }
    }

}
